<template>
  <div>
    <el-input placeholder="商品名称" v-model="info.GoodsName" style="width: 200px;"></el-input>
    商品分类:
    <el-tree-select v-model="info.GoodsTypeId" :data="getgoodsType" check-strictly :render-after-expand="false"
      style="width: 240px" />
    商品标签：
    <el-select-v2 v-model="info.GoodsLabelId" placeholder="请选择" :options="getgoodsLaber" style="width: 240px" />
    <el-button size="large" :icon="Search" round @click="Listss">查询</el-button>


    <el-button type="primary" plain @click="router.push('/GoodsAdd')">添加</el-button>

    <el-button type="primary" plain @click="piliag(1)">批量上架</el-button>
    <el-button type="primary" plain @click="piliag(0)">批量下架</el-button>
    <el-button type="primary" plain @click="del()">批量删除</el-button>
    <el-button type="primary" plain @click="derive()">导出</el-button>

  </div>

  <el-table :data="tableData" style="width: 100%" border ref="multipleTableRef" row-key="GoodsId"
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column fixed prop="GoodsId" label="商品编号" width="150" />
    <el-table-column prop="GoodsName" label="商品名称" width="100" />
    <el-table-column prop="GoodsTyoeName" label="商品分类" width="120" />
    <el-table-column prop="GoodskabelName" label="商品标签" width="90" />
    <el-table-column prop="Price" label="价格" width="100">
      <template #default="scope">
        <span>{{ '￥' + scope.row.Price.toFixed(2) }}</span>
      </template>

    </el-table-column>
    <el-table-column prop="Number" label="库存" width="80" />
    <el-table-column prop="GoodsImages" label="图片" width="130">

      <template #default="scope">
        <img 
          :src="getImageUrl(scope.row.GoodsImages)" 
          width="100" height="100"
          @error="onImgError(scope.row.GoodsImages)"
          @load="onImgLoad(scope.row.GoodsImages)"
        >
      </template>

    </el-table-column>


    <el-table-column prop="GoodsDesc" label="商品明细" width="100">
      <template #default="scope">
        <div v-html="scope.row.GoodsDesc"></div>
      </template>

    </el-table-column>


    <el-table-column prop="Status" label="状态" width="80">
      <template #default="scope">
        <el-tag type="success" v-if="scope.row.Status == 1">上架</el-tag>
        <el-tag type="warning" v-if="scope.row.Status == 0">下架</el-tag>
      </template>

    </el-table-column>



    <el-table-column prop="CreateTime" label="创建时间" width="200">
      <template #default="scope">
        {{ moment(scope.row.CreateTime).format("YYYY-MM-DD HH:mm:ss") }}
      </template>

    </el-table-column>


    <el-table-column fixed="right" label="操作" min-width="180">
      <template #default="scope">


        <el-button type="danger" :icon="Delete" circle @click="Del(scope.row.GoodsId)" />
        <el-button type="primary" :icon="Edit" circle @click="update(scope.row.GoodsId)" />
        <el-button type="success" round @click="stats(scope.row.GoodsId, 1)" v-if="scope.row.Status == 0">上架</el-button>
        <el-button type="danger" round @click="stats(scope.row.GoodsId, 0)" v-if="scope.row.Status == 1">下架</el-button>

      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <table>
    <tr>
      <td>


        <el-pagination v-model:current-page="info.PageIndex" v-model:page-size="info.PageSize"
          :page-sizes="[5, 6, 7, 8]" layout="slot, sizes" :total="info.totalCount" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
          共{{ info.totalCount }}条 每页{{ info.PageSize }}条 第{{ info.PageIndex }}/{{ info.totalPage }}页
        </el-pagination>

      </td>
      <td> <el-pagination v-model:current-page="info.PageIndex" v-model:page-size="info.PageSize"
          :page-sizes="[5, 6, 7, 8]" layout=" slot,prev, pager, next" :total="info.totalCount"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
          <el-button @click="handleCurrentChange(1)" :disabled="info.PageIndex == 1">首页</el-button>

        </el-pagination>

      </td>
      <td> <el-pagination v-model:current-page="info.PageIndex" v-model:page-size="info.PageSize"
          :page-sizes="[5, 6, 7, 8]" layout=" slot,jumper" :total="info.totalCount" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
          <el-button @click="handleCurrentChange(info.totalPage)"
            :disabled="info.PageIndex == info.totalPage">尾页</el-button>
        </el-pagination>


      </td>
    </tr>
  </table>


</template>

<script lang="ts" setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'
import { Check, Delete, Edit, Message, Search, Star, } from '@element-plus/icons-vue'
import type { TableInstance } from 'element-plus'

const apiUrl = import.meta.env.VITE_APP_API_URL;

function getImageUrl(path: string) {
  if (!path) return '';
  if (path.startsWith('http')) return path;
  if (path.startsWith('/img/')) return apiUrl + path;
  if (path.startsWith('img/')) return apiUrl + '/' + path;
  return apiUrl + '/img/' + path.replace(/^\\/, '');
}

function onImgError(path: string) {
  console.log('图片加载失败:', getImageUrl(path));
  // 可选：返回默认图片
  // event.target.src = '/default.png';
}
function onImgLoad(path: string) {
  console.log('图片加载成功:', getImageUrl(path));
}

const router = useRouter()
const route = useRoute()

let info: any = ref({
  PageIndex: 1,
  PageSize: 4,
  GoodsName: '',
  GoodsTypeId: 0,
  GoodsLabelId: 0,
  totalCount: 0,
  totalPage: 0

})

let tableData: any = ref([])

//获取列表
const Listss = () => {
  axios.get('/api/Goods/GetGoodsListPagedAsunc', { params: info.value })
    .then(res => {
      console.log(res);

      tableData.value = res.data.data.data

      info.value.totalCount = res.data.data.totalCount
      info.value.totalPage = res.data.data.totalPage
    })
}


//单删
const Del = (id: any) => {
  console.log(id);
  ElMessageBox.confirm(
    '确定删除吗？',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

      axios({
        url: '/api/Goods/HouseDel',
        method: 'delete',
        params: {
          id: id
        }
      }).then(res => {
        console.log(res);

        if (res.data.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          Listss();

        }


      })


    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除已取消',
      })
    })

}


//上架/下架
const stats = (id: any, stst: any) => {
  console.log(id, stst);
  var opt = "";
  var ss = "";
  if (stst == 1) {
    opt = "上架"
    ss = "新品上市"

  } else {
    opt = "下架"
    ss = "商品过期"
  }

  ElMessageBox.confirm(
    '确定' + opt + '吗？',
    '' + ss + '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

      axios({
        url: '/api/Goods/Shelves',
        method: 'get',
        params: {
          Id: id,
          status: stst
        }
      }).then(res => {
        console.log(res);

        if (res.data.code == 200) {
          ElMessage({
            type: 'success',
            message: '' + opt + '成功',
          })
          Listss();

        }


      })


    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '' + opt + '已取消',
      })
    })


}

//修改
const update = (Id: any) => {
  console.log(Id);
  router.push({
    path: '/GoodsUpdate',
    query: {
      Id: Id
    }
  })





}

let getgoodsType: any = ref([])
let getgoodsLaber: any = ref([])
//商品分类数据
const Typetree = () => {
  axios({
    url: '/api/Goods/GetGoodsTypeListForTreeAsync',
    method: 'post',
    data: {}
  }).then(res => {
    console.log(res);


    getgoodsType.value = res.data.data
    getgoodsType.value.push({ value: 0, label: "全部" })

  })

}
//商品标签
const Laberlist = () => {
  axios({
    url: '/api/Goods/GetGoodsLabelListForSelectasync',
    method: 'get',
    params: {}
  }).then(res => {
    console.log(res);
    if (res.data.code == 200) {
      getgoodsLaber.value = res.data.data;
      getgoodsLaber.value.push({ value: 0, label: "全部" })

    }



  })

}


//全选/反选
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref([])
let Ids: any = ref([])



const handleSelectionChange = (val: any) => {
  //获取页面所有值
  multipleSelection.value = val
  console.log("multipleSelection.value=", multipleSelection.value);

  Ids.value = multipleSelection.value.map((item: any) => {
    return item.GoodsId
  })

  console.log(Ids);

}



const piliag = (Gooid: any) => {
  console.log(Ids, Gooid);
  var dd = ''
  if (Gooid == 0) {
    dd = '下架'
  } else {
    dd = '上架'
  }

  console.log("Ids=", Ids);
  if (Ids.value == 0) {

    ElMessage({ type: 'info', message: '必须选中一项', })
    return;
  }


  ElMessageBox.confirm(
    '' + dd + '操作',
    '商品状态',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

      var data = {
        Ids: Ids.value,
        Stsat: Gooid
      }

      console.log("data=", data)


      axios.put('/api/Goods/UpdateStsat', data).then(res => {
        console.log("res=", res);
        ElMessage({
          type: 'success',
          message: '' + dd + '成功',
        })


        //刷新页面
        Listss()

      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消' + dd + '',
      })
    })

}


//批量删除
const del = () => {
  console.log("Ids=", Ids);

  ElMessageBox.confirm(
    '批量操作',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {




      axios.delete('/api/Goods/Batchdeletion', { data: { GoodsId: Ids.value } }).then(res => {
        console.log("res=", res);
        ElMessage({ type: 'success', message: '删除成功', })
        Listss();

      })




    })
    .catch(() => {
      ElMessage({ type: 'info', message: '批量删除已取消', })
    })



}

//导出
const derive:any = () => {
  location.href = `${apiUrl}/api/Goods/Commodity_export?PageIndex=${info.value.PageIndex}&PageSize=${info.value.PageSize}&GoodsName=${info.value.GoodsName}&GoodsTypeId=${info.value.GoodsTypeId}&GoodsLabelId=${info.value.GoodsLabelId}`;


  //location.href="http://localhost:5167/api/Goods/Commodity_export"
}




onMounted(() => {
  console.log('apiUrl:', apiUrl);
  Listss()
  Typetree()
  Laberlist()

})



const handleClick = () => {
  console.log('click')
}


//分页配置
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  info.value.PageSize = val;
  Listss()
}
//分页配置
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  info.value.PageIndex = val;
  Listss()
}

</script>


<style></style>